package com.gko100.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;


import com.gko100.action.base.AdminBaseAction;
import com.gko100.model.Category;
import com.gko100.model.Image;
import com.gko100.model.Navigation;
import com.opensymphony.xwork2.ActionContext;

public class ImageAction extends AdminBaseAction {
		
	
	private int imageCount;

	public int getImageCount() {
		return imageCount;
	}

	public void setImageCount(int imageCount) {
		this.imageCount = imageCount;
	}
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	private String title;

	private File upload;
		
	private String uploadContentType;
	
	private String uploadFileName;
	
	private String allowTypes;
	
	private String savePath;
	

	private Image image;
	private List<Navigation> navList;
	private String[] checkbox_value;
	private String checkboxListDel;
	public String getCheckboxListDel() {
		return checkboxListDel;
	}
	public void setCheckboxListDel(String checkboxListDel) {
		this.checkboxListDel = checkboxListDel;
	}
	//页面选中项id
	private String[] navIdList;	
	private List<Image> imageList;
	
	public Image getImage() {
		return image;
	}

	public void setImage(Image image) {
		this.image = image;
	}

	public List<Navigation> getNavList() {
		return navList;
	}

	public void setNavList(List<Navigation> navList) {
		this.navList = navList;
	}

	public String[] getCheckbox_value() {
		return checkbox_value;
	}

	public void setCheckbox_value(String[] checkboxValue) {
		checkbox_value = checkboxValue;
	}
	
	public String[] getNavIdList() {
		return navIdList;
	}

	public void setNavIdList(String[] navIdList) {
		this.navIdList = navIdList;
	}

	public List<Image> getImageList() {
		return imageList;
	}

	public void setImageList(List<Image> imageList) {
		this.imageList = imageList;
	}

	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getAllowTypes() {
		return allowTypes;
	}

	public void setAllowTypes(String allowTypes) {
		this.allowTypes = allowTypes;
	}

	
	public String insert_image() throws Exception {
		
		List<Navigation> navList=adminManager.findNavListByNavPId(navPid);
		if(navList!=null){
			for(int i=0;i<navList.size();i++){
				this.setNavList(navList);
			}
		}
		
		return "image_insert_success";
	}
	
	public String add_image() throws Exception {
		
		request = ServletActionContext.getRequest();
    	response = ServletActionContext.getResponse();
        response.setContentType("text\\html; charset=UTF-8");
		
		//允许上传文件类型检测
		
		String filterResult = filterType(this.getAllowTypes().split(","));
		if(filterResult!=null){
			ActionContext.getContext().put("typeError", "图片类型错误");
			return filterResult;
		}
		System.out.println("========"+this.getSavePath()+"\\"+this.getUploadFileName()+"===========");
		
		
		//图片分类
		ActionContext ctx = ActionContext.getContext();
		Navigation nav = adminManager.findNavByNavId(Integer.parseInt(navIdList[0]));
		System.out.println("navId========="+nav.getNavId());
		System.out.println("navId========="+nav.getNavId());
		String navName = null;
		switch(Integer.parseInt(navIdList[0]))
		{
			case 1 : navName="homepage";
			case 2 : navName="medical_service";break;
			case 3 : navName="app_tec";break;
			case 4 : navName="app_ser";break;
			case 5 : navName="medical_service";break;
			case 6 : navName="medical_service";break;
			case 7 : navName="medical_service";break;
			default : navName="nav";break;
		}
		ctx.getSession().put("nav", navName);
		
		//保存时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
		
        String saveUrl = "http://" +request.getServerName() + ":"+request.getServerPort() + request.getContextPath()+"/upload/"+ctx.getSession().get("nav").toString()+"/";
        saveUrl+=ymd+"/";
        
        //图片保存路径
        File dirPath=new File(this.getSavePath()+"\\"+navName+"\\"+ymd);
        
		if(!dirPath.exists()){
			dirPath.mkdirs();
		}
		
		//图片重命名
		String imgName = new Date().getTime()+"_"+new Random().nextInt(1000)+".jpg";
		
		
		//上传图片
		FileOutputStream fos=new FileOutputStream(dirPath+"\\"+imgName);	
		FileInputStream fis=new FileInputStream(this.getUpload());
		byte[] buffer = new byte[1024];
		int len=0;
		while((len=fis.read(buffer))>0){
			fos.write(buffer,0,len);
		}
		
		
		//保存图片到数据库
		Image img=new Image();
		img.setImgSaveName(imgName);
		System.out.println("dirPath================="+dirPath);
		img.setImgUrl(saveUrl+imgName);
		img.setImgSrcName("upload/"+navName+"/"+ymd+"/");
		
		adminManager.add_image(img);
		
		return "image_add_success";
	}
	public String filterType(String[] types) {
		  String fileType = this.getUploadContentType();
		  System.out.println(fileType);
		  for (String type : types) {
		   if (type.equals(fileType)) {
		    return null;
		   }
		  }
		  return INPUT;
	}
	
	public String del_image() throws Exception {
		
		System.out.println(this.getCheckboxListDel());
		String delId[] = this.getCheckboxListDel().split(", ");
		if(delId!=null&&delId.length>=1){
			for(int i=0;i<delId.length;i++){		
				Image image = adminManager.findImgByImgId(Integer.parseInt(delId[i]));
				adminManager.del_imageByImage(image);	
			}
		}else{
			logger.debug(new Exception().getStackTrace()[0].getMethodName()+"------error");
		}
		return "image_del_success";
	}
	
	public String find_imageNavList() throws Exception {
		
		List<Navigation> navList=adminManager.findNavListByNavPId(navPid);
		this.setNavList(navList);
		return "imageNavList_find_success";
	}
	public String find_imageListByNav() throws Exception {
		
		Navigation nav = adminManager.findNavByNavId(Integer.parseInt(this.getNavIdList()[0]));
		List<Image> imageList = adminManager.findImgListByNav(nav);
		this.setImageList(imageList);
		return "imageListByNav_find_success";
	}
	public String find_imageList() throws Exception {
		
		imageCount = adminManager.getImageCount();
		if(imageCount<1){
			
		}
		request = ServletActionContext.getRequest();
		int pageCount = adminManager.getPageCount(imageCount, adminManager.LIST_PAGE_SIZE);
		int pageNo;
		if(request.getParameter("pageNo")==null || request.getParameter("pageNo").trim().equals("")){
			pageNo=1;
		}try {
			
			pageNo=Integer.parseInt(request.getParameter("pageNo").trim());
		}catch (Exception e) {
			pageNo=1;
		}
		if(pageNo>pageCount){
			pageNo=pageCount;
		}
		this.setImageList(adminManager.findImageListAllByPage(pageNo));
		request.setAttribute("pageCount",pageCount);
		request.setAttribute("currentPage",pageNo);
		request.setAttribute("imageList",this.getImageList());
		return "imageList_find_success";
		
	}
}
